package com.walnut.servlet;

import com.walnut.dao.FoodDao;
import com.walnut.dao.impl.FoodDaoImpl;
import com.walnut.pojo.Food;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/updateFood")
public class UpdateFoodServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{}
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        ServletContext context=request.getServletContext();
        Food food= new Food().builder()
                .foodId(Integer.parseInt(request.getParameter("foodId")))
                .foodName(request.getParameter("foodName"))
                .foodImg(request.getParameter("foodImgUrl"))
                .price(Double.parseDouble(request.getParameter("price")))
                .foodStatus(request.getParameter("foodStatus"))
                .build();
        FoodDao foodDao = new FoodDaoImpl();
        try {
            int count = foodDao.update(food);
            if (count==1){
                context.setAttribute("message", "修改成功");
                request.getRequestDispatcher("/foodList").forward(request, response);
            }else {
                context.setAttribute("message", "修改失败,服务器内部错误");
                request.getRequestDispatcher("/foodList").forward(request, response);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
